package base.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 将menu转成json形式的递归菜单
 * @author Kouyq
 *
 */
public class JsonMenu implements java.io.Serializable{

	private static final long serialVersionUID = 1L;
	private static String pk;
	private static String pid;

	/**
	 * 递归函数
	 * @param menulist
	 * @param id
	 * @return
	 */
    private static List<Map<String,Object>> handleSubMenu(List<Map<String,Object>> menulist, String id) {
    	List<Map<String,Object>> rtnlist = new ArrayList<Map<String,Object>>();
    	Iterator<Map<String, Object>> mlist = menulist.iterator();
    	while(mlist.hasNext()){
    		Map<String, Object> menu = mlist.next();
    		if((id != null || "".equals(id)) &&
    				(menu.get(pid) != null || "".equals(menu.get(pid))) &&
    				((String) menu.get(pid)).equalsIgnoreCase(id)){
    			List<Map<String, Object>> list = handleSubMenu(menulist,(String)menu.get(pk));
    			if(list.size() != 0){
    				menu.put("children", list);
				}
    			rtnlist.add(menu);
    		}
    	}
    	return rtnlist;
    }

    /**
     * 生成递归菜单
     * @param objlist
     * @return
     */
    public static <T> List<Map<String, Object>> toJson(List<T> objlist){
    	List<Map<String, Object>> menulist = new ArrayList<Map<String, Object>>();
    	for(T obj:objlist){
    		List<Map<String, Object>> objMap = new ToMapping().parseMapping(obj);
    		Map<String, Object> m = new HashMap<String,Object>();
    		for(Map<String, Object> map:objMap){
    			if(map.equals(objMap.get(0))){
    				pk = (String)map.get("varName");
    			}else if(((String)map.get("varName")).indexOf("id") > -1 || ((String)map.get("varName")).indexOf("sup") > -1){
    				pid = (String)map.get("varName");
    			}
    			m.put((String)map.get("varName"), map.get("varValue"));
    		}
    		menulist.add(m);
    	}
    	List<Map<String, Object>> rtnlist = new ArrayList<Map<String, Object>>();
    	for(Map<String, Object> menu:menulist){
    		if(menu.get(pid) == null || "".equals(menu.get(pid))){
    			List<Map<String, Object>> list = handleSubMenu(menulist, (String)menu.get(pk).toString());
    			if(list.size() != 0){
					menu.put("children", list);
    			}
    			rtnlist.add(menu);
    		}
    	}
    	System.out.println("id:" + pk + ",pid:" + pid);
    	return rtnlist;
    }

}
